//
// 盾头、盾尾的圆形坐标组件
//

import React, { useEffect, useRef, useState } from 'react';
import './index.less';

interface paramsProps {
  title: string;
  width?: number;
  height?: number;
  circleCenter: string;
  x?: any;
  y?: any;
  titles?: any;
}
export default function index(props: paramsProps) {
  let {
    title,
    width = 242,
    height = 240,
    circleCenter,
    x = 100,
    y = -10,
    titles,
  } = props;
  const canvasRef = useRef(null);
  const [pointX, setPointX] = useState(0);
  const [pointY, setPointY] = useState(0);
  let reat = 1.5;
  useEffect(() => {
    let newX;
    if (x >= 0) {
      newX = 120 + Number(x);
      setPointX(newX / reat);
    } else {
      newX = 120 - Math.abs(Number(x));
      setPointX(newX / reat);
    }
  }, [x]);
  useEffect(() => {
    let newY;
    if (y >= 0) {
      newY = 120 - Number(y);
      setPointY(newY / reat);
    } else {
      newY = 120 + Math.abs(Number(y));
      setPointY(newY / reat);
    }
  }, [y]);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');
    width = width / reat;
    height = height / reat;
    const radius = Math.min(width, height) / 2 - 1; // 减去边框宽度
    const centerX = width / 2;
    const centerY = height / 2;

    // 绘制边框和圆
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    ctx.strokeStyle = '#FFF'; // 边框颜色
    ctx.lineWidth = 1; // 边框宽度
    ctx.stroke(); // 绘制边框
    ctx.fillStyle = 'transparent'; // 设置填充颜色为透明
    ctx.fill(); // 填充圆（虽然这里填充的是透明色）

    // 绘制水平和垂直分割线
    ctx.beginPath();
    ctx.moveTo(centerX, 0);
    ctx.lineTo(centerX, height);
    ctx.moveTo(0, centerY);
    ctx.lineTo(width, centerY);

    ctx.strokeStyle = '#FFF'; // 分割线颜色
    ctx.lineWidth = 1; // 分割线宽度
    ctx.stroke(); // 绘制分割线
  }, [width, height]); // 当width或height变化时重新绘制

  return (
    <div className="circle-coordinate">
      <canvas ref={canvasRef} width={width / reat} height={height / reat} />
      <div className={`circle-center ${circleCenter == 'M' ? 'M' : 'N'}`}>
        {circleCenter}
      </div>
      <div
        className="circle-point"
        style={{
          top: pointY,
          left: pointX,
        }}
      >
        <div className="point"></div>
        <div className="point-text">{`${titles.x}:${x} ${titles.y}:${y}`}</div>
      </div>
      <div className="circle-coordinate-title">{title}</div>
    </div>
  );
}
